package com.tanhua.server.server;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.CommentsServiceApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {  //分页查询评论列表(动态id，互动类型=2)
    @DubboReference
    private CommentsServiceApi commentsServiceApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    public PageResult findComments(String movementId, Integer page, Integer pageSize) {
        Integer commentType = 2; //评论
        //1.调api，根据动态id，互动类型，分页查询评论数据 list《comment》
        List<Comment> list = commentsServiceApi.comments(page,pageSize,movementId,commentType);
        //2.判断list是否为空
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }

        List<Long> userId1 = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> ids = userInfoApi.findIds(userId1);
        //3.循环list集合，一个comment构建一个vo
       List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            Long userId = comment.getUserId();
            UserInfo userInfo = ids.get(userId);
            CommentVo vo = CommentVo.init(userInfo, comment);//评论发布人信息，互动对象
            vos.add(vo);
        }
        //4.返回
        return new PageResult(page,pageSize,0l,vos);
    }
  //保存互动评论数据
    public void saveComment(String movementId, String content) {
        //1.创建comment对象，设置属性值
        //publishUser,动态发布人id在api设置
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));  //动态id
        comment.setCommentType(2);
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId()); //评论人
        comment.setCreated(System.currentTimeMillis());
        //2.调api保存，保存后返回评论总数
        Integer count = commentsServiceApi.saveComment(comment);
        System.out.println("评论总数为");
    }
}
